"""
作业
        写一个用户注册系统，输入1注册，输入2查询当前有哪些
        注册：输入用户名，年龄、密码，注册用户放在字典里面，用用户名作为key，其余的作为value
        {"root":{"age":18,"passwd":123456}}
        查询：输入要查询的姓名，展示这个人的详细信息
"""

import os

files_name = "user.txt"


def menu():
    print("-------------------学生信息管理系统--------- -----------------")
    print("----------------------功能菜单--------------------------")
    print("\t\t\t\t\t1.注册用户信息")
    print("\t\t\t\t\t2.查找用户信息")
    print("\t\t\t\t\t0.退出系统")


def register():
    user_list = []
    user_name_lst = []
    while True:
        user_name = input("请输入用户名:")
        if not user_name:
            break
        user_pwd = input("请输入密码:")
        if not user_pwd:
            break
        try:
            user_age = int(input("请输入年龄:"))
        except:
            print("输入不合法！请重新输入")
            continue

        # 将录入的数据保存在字典中
        user = {
            user_name: {
                "user_pwd": user_pwd,
                "user_age": user_age}
        }

        # 将学生信息保存在列表中
        user_list.append(user)
        temp = input("是否继续添加?y/n:")
        if temp == "y" or temp == "Y":
            continue
        else:
            break
    # 保存数据
    save(user_list)


def save(lst):
    try:
        user_txt = open(files_name, "a", encoding="utf-8")
    except:
        user_txt = open(files_name, "w", encoding="utf-8")

    for i in lst:
        user_txt.write(str(i) + "\n")
    user_txt.close()


def select():
    user_list = {}
    while True:
        user_name = input("请输入学生的姓名:")
        with open(files_name, "r", encoding="utf-8") as read_file:
            user = read_file.readlines()
            for i in user:
                d = dict(eval(i))
                user_list.update(d)
            print(user_list[user_name])

            awser = input("是否继续查询:y/n")
            if awser == "y":
                continue
            else:
                break


def main():
    while True:
        menu()
        num = int(input("请选择:"))
        if 2 >= num >= 0:
            if num == 0:
                temp = input("您确定要推出系统吗?y/n:")
                if temp == "y" or temp == "Y":
                    print("感谢您的使用!")
                    break
                else:
                    continue
            elif num == 1:
                register()
            elif num == 2:
                select()
        else:
            print("输入不合法，请重新输入")


if __name__ == '__main__':
    main()
